package com.rongshu.api;

import com.rongshu.base.BuildConfig;
import com.rongshu.utils.Common;
import com.rongshu.view.userInfo.entity.UpLoadImage;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Part;
import retrofit2.http.PartMap;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * created by zhengweis on 2018/12/19.
 * description：
 */
public class FileUploadService {
    private static INewsApi sNewsService;

    private FileUploadService() {
        throw new AssertionError();
    }

    public static void init() {
        LoggingInterceptor loggingInterceptor = new LoggingInterceptor();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (BuildConfig.IS_DEBUG) {
            builder.addInterceptor(loggingInterceptor);
        }
        OkHttpClient okHttpClient = builder
                .retryOnConnectionFailure(true)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(Common.BASE_FILE_HOST)
                .build();
        sNewsService = retrofit.create(INewsApi.class);
    }

    public static Observable<UpLoadImage> upload(@Part MultipartBody.Part file) {
        return sNewsService.uploadOneFile(file)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static Observable<UpLoadImage> uploadMoreFile(@PartMap Map<String, RequestBody> files) {
        return sNewsService.uploadMoreFile(files)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread());
    }
}
